package com.manlost.web.common.download;

import java.io.File;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.manlost.biz.ManlostServiceLocator;
import com.manlost.biz.baby.BabyService;
import com.manlost.biz.baby.model.dataobject.Baby;
import com.manlost.biz.baby.model.dataobject.BabyDraft;
import com.manlost.web.common.BeanCopyUtils;
/**
 * 
 * @author wqq
 *
 */
public class DownloadForBaby implements Runnable {
	BabyService babyService = ManlostServiceLocator.getBabyService();
	private static final Log log=LogFactory.getLog(DownloadForBaby.class);
	private List<BabyDraft> downloadTask;
	private static final String DEFAULT_IMAGE_TYPE=".jpg";
	
	public List<BabyDraft> getDownloadTask() {
		return downloadTask;
	}

	public void setDownloadTask(List<BabyDraft> downloadTask) {
		this.downloadTask = downloadTask;
	}
	
	public String getFileType(String fileName){
		if(StringUtils.isBlank(fileName)){
			return DEFAULT_IMAGE_TYPE;
		}
		int index=fileName.lastIndexOf(".");
		int indexLastSp=fileName.lastIndexOf("/");
		return index>0&&indexLastSp<index?fileName.substring(index,fileName.length()):DEFAULT_IMAGE_TYPE;
	}


	@Override
	public void run() {
		if(this.downloadTask==null||this.downloadTask.size()==0){
			return ;
		}
		HttpDownload download = new HttpDownload();
		//连接ftp
		download.openFtp();
		for(BabyDraft babyDraft:downloadTask){
			System.out.println("babyDraft---id----"+babyDraft.getId());
			FileInfo fileInfo=new FileInfo();
			Map<String,String> dirs=new LinkedHashMap<String,String>();
			dirs.put(babyDraft.getBabyYear(),null);
			dirs.put(babyDraft.getBabyMonthDate(),null);
			fileInfo.setDirs(dirs);
			fileInfo.setPath(babyDraft.getBabyYear()+File.separator+babyDraft.getBabyMonthDate());
			String fileName=babyDraft.getId()+getFileType(babyDraft.getUri());
			fileInfo.setFileName(fileName);
			download.addItem(babyDraft.getUri(),fileInfo);
			//set image info
			babyDraft.setImageLa(fileInfo.getPath()+File.separator+fileName);
			babyDraft.setImageMi(fileInfo.getPath()+File.separator+fileName);
		}
		try {
			//下载
			download.downLoadByList();
			//关闭ftp
			download.closeFtp();
			//copy baby
			List<Baby> babies=BeanCopyUtils.copyList(downloadTask,Baby.class);
			babyService.inserBabies(babies);
		} catch (Exception e) {
			log.error("urls-------"+download.getDownloadUrls()+" -----------download error!",e);
		}
	}
	
}
